$(document).ready(function() {
	$("#regUser").click(function(){
		window.location.href = "/user/registerUI";
	});


	/**
	 * web socket
	 */
	var socket = null;
	
	/**
	 * 聊天记录root容器, key = alias, value = msgs
	 */
	var msgPack = {};
	
	/**
	 * 聊天子容器(单对单), 存放msg
	 */
	var msgs = new Array();
	
	/**
	 * 聊天记录对象
	 * 注意: isSend = ture是当前用户对msgPack.key通信, false是msgPack.key对当前用户进行通信
	 */	
	var Msg = function(time, isSend, text){
		this.time = time;
		this.isSend = isSend;
		this.text = text;
	}
	
	/**
	 * QQ_TalkUtil
	 */
	var QQ_TalkUtil = function (socket){
		this._aliasSpan = $("#alias_span");
		this._userMark = $("#user_mark");
		this.url;
		this.socket = socket;
		this.interValId;
		this.addr;
		this.post;
		this.alias;
		this.reconnetion = true;
		this.recannetionTime = 1000;
		this.aimUser;
	};

	var Request = function(code, alias, context, aimAlias){
		this.code = code;
		this.alias = alias;
		this.context = context;
		this.aimAlias = aimAlias;
	};
	
	var reconnetionId;
	
	/**
	 * 连接web socket
	 */
	QQ_TalkUtil.prototype.connetionSocket = function (addr, post, alias) {
	
		socket = new WebSocket("ws://"+this.addr+":"+this.post+"/name="+this.alias);
		socket.util = this;
		
		socket.onopen = function (event) {
			console.log("已建立连接!");
			//TODO 发送查找当前在线用户
			var request = new Request("findAllUser", this.util.alias);
			this.send(JSON.stringify(request));
			console.log(event);
		};
		
		socket.onmessage = function (event) {
			console.log("onmessage");
			console.log(event);
			//不同按照不同code来更新页面
			var data = jQuery.parseJSON(event["data"]);
			var code = data.code;
			var context = data.context;
			var time = data.hour;

			console.log("code="+code+", context="+context);

			if(code == "onLine") //上线
			{
				this.util.addList(context, time);
			}
			else if(code == "outLine") //下线
			{
				this.util.removeList(context);
			}
			else if(code == "msg") //接收到消息
			{
				var sendAlias = data.alias;
				//渲染页面
				$("#qq_list").find("li[alias="+sendAlias+"]").find(".qq-hui-txt").text(context);
				//记录聊天记录
				this.util.saveMsg(sendAlias, context, time, false);
			}
		};
		
		socket.onerror = function (event) {
			socket.close();
		};
		
		socket.onclose = function (event) {
			if(this.util.reconnetion == true) {
				this.util.removeAllList();
				setTimeout(this.util.connetionSocket() ,this.util.recannetionTime);
			}
			console.log("连接已关闭!");
		};

	};



	QQ_TalkUtil.prototype.showQQ_Talk = function (){
		if ($('.login-txt').find('input').val() == '') {
			alert('error1')
		} else if ($('login-txt input').val() != '') {
			$('.qq').css('display', 'block').removeClass('mins')
			$('.qq-login').css('display', 'none')
		}
	};

	/**
	 * 添加用户列表
	 */
	QQ_TalkUtil.prototype.addList = function (name, time){
		var _list = "<li alias="+name+">"
		+ "<div class='qq-hui-img'><img src='/images/head/01.jpg'><i></i></div>"
		+ "<div class='qq-hui-name'><span>"+name+"</span><i>"+time+"</i></div>"
		+ "<div class='qq-hui-txt' title=''>TODO</div>"
		+ "</li>";
		$("#qq_list").append(_list);
	};

	/**
	 * 根据用户名删除用户列表
	 */
	QQ_TalkUtil.prototype.removeList = function(name) {
		$("#qq_list").find("li[alias="+name+"]").remove();
	};


	QQ_TalkUtil.prototype.removeAllList = function() {
		$("#qq_list").find("li").remove();
	};

	//登录ajax发送
	QQ_TalkUtil.prototype.loginAjax = function (){
		//AJAX验证用户名, 密码
		var username = $("#username").val();
		var password = $("#password").val();
		var self = this;
		$.ajax({
			async : false,
			url : "/user/login",
			data : {"username" : username, "password" : password},
			success : function(msg) {
				if(msg.code == "success") {
					//加入netty长连接, 获取所有在线用户信息
					talkUtil.addr = msg.socketAddr;
					talkUtil.post = msg.socketPost;
					talkUtil.alias = msg.alias;
					talkUtil.reconnetion = true;
					talkUtil.connetionSocket();
					talkUtil._aliasSpan.text(msg.alias);
					self.showQQ_Talk();
				}else {
					alert("用户名或密码错误!")
				}
			}
		});
	};
	
	QQ_TalkUtil.prototype.saveMsg = function (aimAlias, text, time, isSend) {
		 
		var msgs = msgPack[aimAlias];
		if(msgs == null) {
			msgs = new Array();
			msgPack[aimAlias] = msgs;
		}
		var msg = new Msg(time, isSend, text);
		msgs.push(msg);
		
		console.log(msgPack);
	};
	
	/**
	 * 加载对应alias的聊天记录
	 */
	QQ_TalkUtil.prototype.loadMsg = function (alias) {
		
		$("#msg").find("li").remove();
		console.log("=======");
		var msgs = msgPack[alias];
		
		for(index in msgs) {
			var msg = msgs[index];
			
			var time = msg.time;
			var text = msg.text;
			var isSend = msg.isSend;
			
			if(isSend == true) {
				
				/*var _li = '<li class="my" >' +
						  '<div class="qq-chat-my" ><span>' + this.alias + '</span>' +
						  '<i>' + time + '</i>' +
						  '</div>' +
						  '<div class="qq-chat-ner" >' + text + '</div>' +
						  '</li>';*/
				var _li = "<li class='my'>" +
				"<div class='qq-chat-my'>" +
				"<span>" + this.alias + "</span>" +
				"<i>" + time + "</i>" +
				"</div>" +
				"<div class='qq-chat-ner'>" + text + "</div>" +
				"</li>";
	
				$("#msg").append(_li);
			}else if(isSend == false) {
				var _li = "<li>" +
				"<div class='qq-chat-you blue'>" +
				"<span>" + alias + "</span>" +
				"<i>" + time + "</i>" +
				"</div>" +
				"<div class='qq-chat-ner'>" + text + "</div>" +
				"</li>";
				console.log("_li="+_li);
				$("#msg").append(_li);
			}
		}
		
		
	};
	
	

	var talkUtil = new QQ_TalkUtil(socket);

	//打开QQ界面
	function showQQ_Talk() {
		if ($('.login-txt').find('input').val() == '') {
			alert('error1')
		} else if ($('login-txt input').val() != '') {
			$('.qq').css('display', 'block').removeClass('mins')
			$('.qq-login').css('display', 'none')
		}
	}

	//回车登录
	$('.login-txt input').keydown(function(e) {
		if (e.keyCode == 13) {
			if ($('.login-txt').find('input').val() == '') {
				alert('请输入账号和密码')
			} else if ($('login-txt input').val() != '') {
				talkUtil.loginAjax();
			}
		}
	})

	//登录按钮
	$('.login-but').click(function() {
		talkUtil.loginAjax();
	})

	//关闭
	$('.close').click(function() {
		if($(this).hasClass("qq-top-02")) {
			talkUtil.reconnetion = false;
			//断开连接
			socket.close();
			talkUtil.removeAllList();
		}
		else if($(this).hasClass("msg_window")) {
			talkUtil.aimUser = null;
		}
			
		
		$(this).parent().parent().parent().css('display', 'none')
	})

	//打开聊天框
	$("#qq_list").on("dblclick", "li", function(){
		
		talkUtil.aimUser = $(this).attr("alias");
		
		//TODO 对这个用户的对话记录信息重新渲染
		/*$('.qq-chat-you span').html($(this).find('span').html());
		$('.qq-chat-you i').html($(this).find('.qq-hui-name i').html());*/
		talkUtil.loadMsg(talkUtil.aimUser);
		
		
		$('.qq-chat').css('display', 'block').removeClass('mins');
		$('.qq-chat-t-name').html($(this).find('span').html());
		$('.qq-chat-t-head img').attr('src', $(this).find('img').attr('src'));
		
		$('.qq-chat-ner').html($(this).find('.qq-hui-txt').html());
		$("#qq-chat-text").trigger("focus");
		$('.my').remove()
	});

	//发送内容
	$('.fasong').click(function() {
        if ($('#qq-chat-text').val() == '') {
            alert("error3")
        } else if ($('#qq-chat-text').val() != '') {
        	
        	//发送内容, 接收到服务器响应后, 渲染页面
        	var text = $('#qq-chat-text').val()
        	var now = new Date()
        	var t_div = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + ' ' + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
        	var request = new Request("sendTo", talkUtil.alias, text, talkUtil.aimUser);
        	//保存聊天记录
        	socket.send(JSON.stringify(request));
        	talkUtil.saveMsg(talkUtil.aimUser, text, t_div, true);
        	
            var name = $('.qq-top-name span').html()
            var ner = $('#qq-chat-text').val()
            var ners = ner.replace(/\n/g, '<br>')
            
           
            $('.qq-chat-txt ul').append('<li class="my"><div class="qq-chat-my"><span>' + name + '</span><i>' + t_div + '</i></div><div class="qq-chat-ner">' + ners + '</div></li>')
            $(".qq-chat-txt").scrollTop($(".qq-chat-txt")[0].scrollHeight);
            $('#qq-chat-text').val('').trigger("focus")
        }
    })
	
});